package com.qianyu.project.core.utils;


import com.qianyu.project.core.annotation.FlowEntry;
import com.qianyu.project.core.exception.PrimaryKeyNotFoundException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author gs
 * @date create in 2020/12/12 8:15
 */
public class FlowEntryHandler {

    /**
     * description: 解析FlowEntry拿到主键值 <br/>
     * author: gs   <br/>
     * date: 2020/12/18 <br/>
     * params: [] <br/>
     * return: java.lang.Object
     */
    public static Object parseFlowEntry(Method method, Object[] args) throws PrimaryKeyNotFoundException {
        FlowEntry flowEntry = null;
        int index = -1;
        //获取方法参数注解
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterAnnotations.length; i++) {
            for (int j = 0; j < parameterAnnotations[i].length; j++) {
                //判断是否是FlowEntry注解
                if (parameterAnnotations[i][j].annotationType() == FlowEntry.class) {
                    flowEntry = (FlowEntry) parameterAnnotations[i][j];
                    index = i;
                }
            }
        }
        //判断是否取到了注解
        Assert.flowEntryNotNull(flowEntry);
        //拿到注解对应的参数
        Object entry = args[index];
        //拿到主键字段
        String value = flowEntry.value();
        //解析class拿到主键字段值并返回
        return getPrimaryKeyValue(entry, value);
    }

    /**
     * description: 拿到主键值 <br/>
     * author: gs   <br/>
     * date: 2020/12/18 <br/>
     * params: [type, fieldName] <br/>
     * return: java.lang.Object
     */
    private static Object getPrimaryKeyValue(Object entry,String fieldName) {
        //拿到对象的类型
        Class type = entry.getClass();
        Field[] fields = type.getDeclaredFields();
        Object result = null;
        for (Field field : fields){
            if(field.getName().equals(fieldName)){
                StringBuilder builder = new StringBuilder("get");
                builder.append(field.getName().substring(0, 1).toUpperCase())
                        .append(field.getName().substring(1));
                try {
                    Method method = type.getMethod(builder.toString());
                    result = method.invoke(entry);
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        return result;
    }
}
